package com.example.springbootwebsocketmonikehuduan.udpcleit;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.HashMap;

/**
 * @program: springboot-websocket-monikehuduan
 * @description:
 * @author: XianJin.Lu
 * @create: 2021-09-12 09:13
 **/
public class UDPServer {
    public static void main(String[] args) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        /*
         * 接收客户端发送的数据
         */
        // 1.创建服务器端DatagramSocket，指定端口
        DatagramSocket socket = new DatagramSocket(7700);
        // 2.创建数据报，用于接收客户端发送的数据
        int m =0;
        while(m<6) {

            byte[] data = new byte[2048];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            // 3.接收客户端发送的数据
            System.out.println("****服务器端已经启动，等待客户端发送数据");
            socket.receive(packet);// 此方法在接收到数据报之前会一直阻塞
            // 4.读取数据
            String info = new String(data, 0, packet.getLength());
            if (info.equals("结束")){
                m=6;
                socket.close();
                return;
            }
            int i = info.indexOf(',');
            int j = info.lastIndexOf('}');

            //电话总数封装
            String firstJsonStr = info.substring(0, i)+"}";
            map.put("total", JSON.parse(firstJsonStr));


            String seconedJsonStr = info.substring(i+1, j);
            map.put("status",JSON.parse(seconedJsonStr));

            System.out.println("客户端数据：" + info);

            String total = map.get("total").toString();
            System.out.println(total);
            String status = map.get("status").toString();
            System.out.println(status);
        }

        // 4.关闭资源
        try {
            socket.close();
        } catch (Exception e) {
            System.out.println("异常处结束");
            e.printStackTrace();
        }
    }
}
